
<template>
  <div class="pt-10 flex">
    <div class="SelectOption" @click="handleClick2(index)" v-if="isDs">
      <div class="select-box ds">
        <span>{{ dsName }}</span>
        <img src="@/assets/imgs/electricity/selectj.png" alt="" v-show="ds" />
        <img src="@/assets/imgs/electricity/selectj2.png" alt="" v-show="!ds" />
      </div>
      <div
        class="options"
        :style="{ height: ds ? '140px' : '0', width: '200px' }"
      >
        <div style="height: 100%; overflow: auto">
          <div
            v-for="(i, d) in dsOptions"
            :key="d"
            class="option"
            @click.stop="handleOptionClick2(i.text)"
          >
            <span
              :class="['option-text', dsName.indexOf(i.text) > -1 ? 'on2' : '']"
              :title="i.text"
              style="width: auto"
              >{{ i.text }}</span
            >
          </div>
        </div>
        <div class="sure-btn" @click.stop="dsSureClick">确认</div>
      </div>
    </div>
    <template v-for="(item, index) in list">
      <div
        class="SelectOption"
        @click="handleClick(index)"
        :key="index"
        v-if="item.show"
      >
        <div class="select-box" :style="{ width: item.width + 'px' }">
          <span>{{ item.title }}</span>
          <img
            src="@/assets/imgs/electricity/selectj.png"
            alt=""
            v-show="item.showOptions"
          />
          <img
            src="@/assets/imgs/electricity/selectj2.png"
            alt=""
            v-show="!item.showOptions"
          />
        </div>
        <div
          class="options"
          :style="{ height: item.showOptions ? '140px' : '0' }"
        >
          <div
            v-for="(option, index2) in item.options"
            :key="index2"
            class="option"
            @click.stop="handleOptionClick(index, index2)"
          >
            <span
              :class="['option-text', option.text === item.title ? 'on' : '']"
              >{{ option.text }}</span
            >
          </div>
        </div>
      </div>
    </template>
    <!-- <div class="search-box" @click="searchClick">
      <img src="@/assets/imgs/electricity/search-icon.png" alt="搜索图标" />
      <span>搜索</span>
    </div> -->
  </div>
</template>
<script>
import { reactive, ref, onMounted, onBeforeUnmount, nextTick } from "vue";
import * as mapData from "@/utils/sichuan";
import { ElMessage } from "element-plus";
export default {
  props: {
    isDs: {
      type: Boolean,
      default: false,
    },
  },

  setup(props, { emit }) {
    let ds = ref(false);
    let dsName = ref("地市");
    let dsOptions = reactive([]);
    const arr = mapData.default.features;
    arr.forEach((item) => {
      dsOptions.push({
        text: item.properties.name,
        value: item.properties.name,
      });
    });
      dsOptions.push({
      text: "天府",
      value: "天府",
    });
    dsOptions.push({
      text: "岷江",
      value: "岷江",
    });
  
    // 数据级别下拉数据
    let options = reactive([
      { text: "年", value: "year" },
      { text: "月", value: "month" },
      { text: "日", value: "day" },
      { text: "小时", value: "hour" },
      { text: "分钟", value: "minute" },
    ]);
    let optionsY = reactive([]);
    // 获取当前年份
    const currentYear = new Date().getFullYear();
    // 计算往前推5年的年份
    const fiveYearsAgo = currentYear - 5;
    // 计算往后推5年的年份
    const fiveYearsLater = currentYear + 5;
    // 获取当前月
    const currentMonth = new Date().getMonth() + 1;
    // 获取当前日
    const currentDay = new Date().getDate();
    // 获取当前小时
    const currentHour = new Date().getHours();
    // 获取当前分钟
    const currentMinute = new Date().getMinutes();
    let yearArr = [];
    for (let i = fiveYearsAgo; i <= fiveYearsLater; i++) {
      yearArr.push({ text: i, value: i });
    }
    optionsY = yearArr;

    let optionsM = reactive([]);
    for (let i = 1; i <= 12; i++) {
      optionsM.push({ text: i, value: i });
    }
    let optionsD = reactive([]);
    let optionsH = reactive([]);
    for (let j = 1; j <= 24; j++) {
      optionsH.push({ text: j, value: j });
    }
    let optionsS = reactive([]);
    for (let k = 1; k <= 59; k++) {
      optionsS.push({ text: k, value: k });
    }
    function getAllDaysInMonth(year, month) {
      // 注意：JavaScript中的月份是从0开始的，所以1月是0，2月是1，以此类推。
      // 因此，需要将传入的月份参数减1。
      month = month - 1;
      let date = new Date(year, month, 1);
      let days = [];

      while (date.getMonth() === month) {
        days.push({
          text: new Date(date).getDate(),
          value: new Date(date).getDate(),
        });
        date.setDate(date.getDate() + 1);
      }

      return days;
    }
    // 获取当前年月的所有日期
    optionsD = getAllDaysInMonth(currentYear, currentMonth);

    let list = reactive([
      {
        title: "数据级别",
        options: options,
        showOptions: false,
        show: true,
        width: 94,
      },
      {
        title: "年", //年
        options: optionsY,
        showOptions: false,
        show: true,
        width: 84,
      },
      {
        title: "月", //月
        options: optionsM,
        showOptions: false,
        show: true,
        width: 73,
      },
      {
        title: "日", //日
        options: optionsD,
        showOptions: false,
        show: true,
        width: 69,
      },
      // {
      //   title: currentHour, //小时
      //   options: optionsH,
      //   showOptions: false,
      //   show: false,
      //   width: 69,
      // },
      // {
      //   title: currentMinute, //分钟
      //   options: optionsS,
      //   showOptions: false,
      //   show: false,
      //   width: 69,
      // },
    ]);
    // 地市多选 选择单独处理
    const handleClick2 = () => {
      ds.value = !ds.value;
      list.forEach((item) => {
        item.showOptions = false;
      });
    };
    const handleOptionClick2 = (name) => {
      let arr = dsName.value ? dsName.value.split(",") : [];
      if (dsName.value.indexOf(name) === -1) {
        if (arr.length >= 5) {
          ElMessage.warning("最多只能选择5个地市,请点击取消选择后再选择");
          return;
        } else {
          arr.push(name);
        }
      } else {
        arr.splice(arr.indexOf(name), 1);
      }
      dsName.value = arr.length ? arr.join(",").replace("地市,", "") : "地市";
    };
    const dsSureClick = () => {
      ds.value = false;
      emit("changeds", dsName.value);
    };
    // 单选
    const handleClick = (i) => {
      list[i].showOptions = !list[i].showOptions;
      list.forEach((item, index) => {
        if (index !== i) {
          item.showOptions = false;
        }
      });
      if (ds.value) {
        ds.value = false;
      }
    };
    const handleOptionClick = (i, i2) => {
      if (i != 0 && list[0].title == "数据级别") {
        ElMessage.warning("请先选择数据级别");
        return;
      }
      list[i].showOptions = false;
      list[i].options[i2].title = false;
      list[i].title = list[i].options[i2].text;
      list[1].title = list[1].title !== "年" ? list[1].title : currentYear;
      list[2].title = list[2].title !== "月" ? list[2].title : currentMonth;
      list[3].title = list[3].title !== "日" ? list[3].title : currentDay;
      list[3].options = getAllDaysInMonth(list[1].title, list[2].title);
      // 选择月份后需重新选择日
      if (i == 2) {
        list[3].title = "日";
      }
      // 数据级别选择处理
      switch (list[i].title) {
        case "年":
          for (let i = 1; i < 4; i++) {
            list[i].show = i < 1 ? true : false;
          }
          break;
        case "月":
          for (let i = 1; i < 4; i++) {
            list[i].show = i < 2 ? true : false;
          }
          break;
        case "日":
          for (let i = 1; i < 4; i++) {
            list[i].show = i < 3 ? true : false;
          }
          break;
        case "小时":
          for (let i = 1; i < 4; i++) {
            list[i].show = i < 4 ? true : false;
          }
          // for (let i = 1; i < 6; i++) {
          //   list[i].show = i < 5 ? true : false;
          // }
          break;
        case "分钟":
          for (let i = 1; i < 4; i++) {
            list[i].show = i < 4 ? true : false;
          }
          // for (let i = 1; i < 6; i++) {
          //   list[i].show = i < 6 ? true : false;
          // }
          break;
        default:
          break;
      }
      searchClick();
    };
    const searchClick = () => {
      console.log(list);
      emit("change", list);
    };
    const closeDropdownIfClickedOutside = function (event) {
      let dropdown = document.querySelector(".SelectOption");
      console.log(dropdown && !dropdown.contains(event.target));
      if (dropdown && !dropdown.contains(event.target)) {
        console.log("closeDropdownIfClickedOutside");
        list.map((item) => {
          item.showOptions = false;
        });
      }
    };
    onMounted(() => {
      // document.addEventListener("click", closeDropdownIfClickedOutside);
    });
    onBeforeUnmount(() => {
      document.removeEventListener("click", closeDropdownIfClickedOutside);
    });
    return {
      handleClick,
      handleOptionClick,
      list,
      dsOptions,
      ds,
      dsName,
      handleClick2,
      handleOptionClick2,
      searchClick,
      dsSureClick,
    };
  },
};
</script>
<style lang="scss" scoped>
.SelectOption {
  position: relative;
  // width: 94px;
  height: 31px;
  background: url("@/assets/imgs/electricity/selectbg.png") no-repeat center;
  background-size: 100% 100%;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  margin: 10px 10px 0 0;
  .select-box {
    span {
      color: #c7e1ff;
      font-size: 14px;
      font-family: "阿里巴巴普惠体";
      line-height: 30px;
      padding: 0 0 0 10px;
    }
    img {
      width: 18px;
      height: 17px;
      position: absolute;
      right: 5px;
      top: 7px;
      z-index: 1;
    }
    &.ds {
      span {
        display: inline-block;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        width: 65px;
      }
    }
  }
  .options {
    position: absolute;
    top: 31px;
    left: 0;
    width: 100%;
    background: url("@/assets/imgs/electricity/selectCon.png") no-repeat center;
    background-size: 100% 100%;
    z-index: 2;
    overflow: auto;
    transition: all 0.2s ease-in-out;
    .sure-btn {
      width: 61px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      position: absolute;
      right: 0;
      bottom: 0;
      background: url("@/assets/imgs/electricity/search-bg.png") no-repeat
        center;
      background-size: 100% 100%;
      cursor: pointer;
      margin: 0 0 0 10px;
      color: rgba(199, 225, 255, 1);
      font-size: 12px;
      font-family: "苹方中等";
      margin-left: 5px;
    }
  }
}
.pt-10 {
  padding-left: 5px;
}
.option-text {
  width: 78px;
  height: 22px;
  line-height: 22px;
  color: #c7e1ff;
  font-size: 14px;
  font-family: "阿里巴巴普惠体";
  display: block;
  padding: 0 0 0 10px;
  margin: 5px 0 0 10px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  &:hover {
    background: url("@/assets/imgs/electricity/selectOp.png") no-repeat left
      center;
  }
  &.on {
    background: url("@/assets/imgs/electricity/selectOp.png") no-repeat left
      center;
  }
  &.on2 {
    color: #40cce6;
  }
}
/* 针对WebKit浏览器（如Chrome、Safari） */
::-webkit-scrollbar {
  display: none;
}

/* 针对Firefox浏览器 */
* {
  scrollbar-width: none; /* 可选项：自动（auto）或无（none） */
}
.flex {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.search-box {
  width: 61px;
  height: 31px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("@/assets/imgs/electricity/search-bg.png") no-repeat center;
  background-size: 100% 100%;
  cursor: pointer;
  margin: 10px 0 0;
  span {
    color: rgba(199, 225, 255, 1);
    font-size: 12px;
    font-family: "苹方中等";
    margin-left: 5px;
  }
  img {
    width: 10px;
    height: 10px;
    vertical-align: middle;
  }
}
</style>